/* USER VARIABLES */
var numberOfColumns = 6;	// Number of columns for dragable boxes
var columnParentBoxId = 'ordenesPrincipal';	// Id of box that is parent of all your dragable boxes
var src_rightImage = '../imagenes/arrow_right.gif';
var src_downImage = '../imagenes/arrow_down.gif';
	
var transparencyWhenDragging = false;
var autoScrollSpeed = 4;	// Autoscroll speed	- Higher = faster	
var dragObjectBorderWidth = 1;	// Border size of your RSS boxes - used to determine width of dotted rectangle
var hideBoxes = 0; //Expands or compresses boxes
var resids = new Array(new Array(), new Array(), new Array(), new Array(), new Array(),new Array()); // Solution mirror array for extra purposes.
var imgHeight = new Array(0,0,0,0,0,0);
var boxMaxHeight = 130;
var boxMinHeight = 30;
/* END USER VARIABLES */
	
var columnParentBox;
var dragableBoxesObj;
	
var boxIndex = 0;	
var autoScrollActive = false;
var dragableBoxesArray = new Array();
	
var dragDropCounter = -1;
var dragObject = false;
var dragObjectNextSibling = false;
var dragObjectParent = false;
var destinationObj = false;
	
var mouse_x;
var mouse_y;
	
var el_x;
var el_y;	
	
var rectangleDiv;
var okToMove = true;

var documentHeight = false;
var documentScrollHeight = false;
var dragableAreaWidth = false;
		
var opera = navigator.userAgent.toLowerCase().indexOf('opera')>=0?true:false;
	
var staticObjectArray = new Array();
	
function autoScroll(direction,yPos){
    if(document.documentElement.scrollHeight>documentScrollHeight && direction>0)return;
    if(opera)return;
    window.scrollBy(0,direction);
    if(!dragObject)return;
		
    if(direction<0){
        if(document.documentElement.scrollTop>0){
            dragObject.style.top = (el_y - mouse_y + yPos + document.documentElement.scrollTop) + 'px';		
        }else{
            autoScrollActive = false;
        }
    }else{
        if(yPos>(documentHeight-50)){	
            dragObject.style.top = (el_y - mouse_y + yPos + document.documentElement.scrollTop) + 'px';			
        }else{
            autoScrollActive = false;
        }
    }
    if(autoScrollActive)setTimeout('autoScroll('+direction+',' + yPos + ')',5);
}
		
function initDragDropBox(e){
    dragDropCounter = 1;
    if(document.all)e = event;
		
    if (e.target) source = e.target;
    else if (e.srcElement) source = e.srcElement;
    if (source.nodeType == 3) // defeat Safari bug
        source = source.parentNode;
		
    if(source.tagName.toLowerCase()=='img' || source.tagName.toLowerCase()=='a' || source.tagName.toLowerCase()=='input' || source.tagName.toLowerCase()=='td' || source.tagName.toLowerCase()=='tr' || source.tagName.toLowerCase()=='table')return;
	
    mouse_x = e.clientX;
    mouse_y = e.clientY;	
    var numericId = this.id.replace(/[^0-9]/g,'');
    el_x = getLeftPos(this.parentNode.parentNode)/1;
    el_y = getTopPos(this.parentNode.parentNode)/1 - document.documentElement.scrollTop;
			
    dragObject = this.parentNode.parentNode;
		
    documentScrollHeight = document.documentElement.scrollHeight + 100 + dragObject.offsetHeight;
		
    if(dragObject.nextSibling){
        dragObjectNextSibling = dragObject.nextSibling;
        if(dragObjectNextSibling.tagName!='DIV')dragObjectNextSibling = dragObjectNextSibling.nextSibling;
    }
    dragObjectParent = dragableBoxesArray[numericId]['parentObj'];
			
    dragDropCounter = 0;
    initDragDropBoxTimer();	
    return false;
}
	
	
function initDragDropBoxTimer(){
    if(dragDropCounter>=0 && dragDropCounter<10){
        dragDropCounter++;
        setTimeout('initDragDropBoxTimer()',10);
        return;
    }
    if(dragDropCounter==10){
        mouseoutBoxHeader(false,dragObject);
    }
}

function moveDragableElement(e){


    if(document.all)e = event;
    if(dragDropCounter<10)return;

    if(document.all && e.button!=1 && e.button && !opera){
        stop_dragDropElement();
        return;
    }

    if(document.body!=dragObject.parentNode){
        dragObject.style.width = (dragObject.offsetWidth - (dragObjectBorderWidth*2)) + 'px';
        dragObject.style.position = 'absolute';	
        dragObject.style.textAlign = 'left';
        if(transparencyWhenDragging){	
            dragObject.style.filter = 'alpha(opacity=70)';
            dragObject.style.opacity = '0.7';
        }	
        dragObject.parentNode.insertBefore(rectangleDiv,dragObject);
        rectangleDiv.style.display='block';
        document.body.appendChild(dragObject);

        rectangleDiv.style.width = dragObject.style.width;
        rectangleDiv.style.height = (dragObject.offsetHeight - (dragObjectBorderWidth*2)) + 'px'; 
    }
		
    if(e.clientY<50 || e.clientY>(documentHeight-50)){
        if(e.clientY<50 && !autoScrollActive){
            autoScrollActive = true;
            autoScroll((autoScrollSpeed*-1),e.clientY);
        }
			
        if(e.clientY>(documentHeight-50) && document.documentElement.scrollHeight<=documentScrollHeight && !autoScrollActive){
            autoScrollActive = true;
            autoScroll(autoScrollSpeed,e.clientY);
        }
    }else{
        autoScrollActive = false;
    }		

    var leftPos = e.clientX;
    var topPos = e.clientY + document.documentElement.scrollTop;
		
    dragObject.style.left = (e.clientX - mouse_x + el_x) + 'px';
    dragObject.style.top = (el_y - mouse_y + e.clientY + document.documentElement.scrollTop) + 'px';
		
    if(!okToMove)return;
    okToMove = false;

    destinationObj = false;	
    rectangleDiv.style.display = 'none'; 
		
    var objFound = false;
    var tmpParentArray = new Array();
		
    if(!objFound){
        for(var no=1;no<dragableBoxesArray.length;no++){
            if(dragableBoxesArray[no]['obj']==dragObject)continue;
            tmpParentArray[dragableBoxesArray[no]['obj'].parentNode.id] = true;
            if(!objFound){
                var tmpX = getLeftPos(dragableBoxesArray[no]['obj']);
                var tmpY = getTopPos(dragableBoxesArray[no]['obj']);

                if(leftPos>tmpX && leftPos<(tmpX + dragableBoxesArray[no]['obj'].offsetWidth) && topPos>(tmpY-20) && topPos<(tmpY + (dragableBoxesArray[no]['obj'].offsetHeight/2))){
                    destinationObj = dragableBoxesArray[no]['obj'];
                    destinationObj.parentNode.insertBefore(rectangleDiv,dragableBoxesArray[no]['obj']);
                    rectangleDiv.style.display = 'block';
                    objFound = true;
                    break;
						
                }
                if(leftPos>tmpX && leftPos<(tmpX + dragableBoxesArray[no]['obj'].offsetWidth) && topPos>=(tmpY + (dragableBoxesArray[no]['obj'].offsetHeight/2)) && topPos<(tmpY + dragableBoxesArray[no]['obj'].offsetHeight)){
                    objFound = true;
                    if(dragableBoxesArray[no]['obj'].nextSibling){
							
                        destinationObj = dragableBoxesArray[no]['obj'].nextSibling;
                        if(!destinationObj.tagName)destinationObj = destinationObj.nextSibling;
                        if(destinationObj!=rectangleDiv)destinationObj.parentNode.insertBefore(rectangleDiv,destinationObj);
                    }else{
                        destinationObj = dragableBoxesArray[no]['obj'].parentNode;
                        dragableBoxesArray[no]['obj'].parentNode.appendChild(rectangleDiv);
                    }
                    rectangleDiv.style.display = 'block';
                    break;					
                }
                if(!dragableBoxesArray[no]['obj'].nextSibling && leftPos>tmpX && leftPos<(tmpX + dragableBoxesArray[no]['obj'].offsetWidth)
                    && topPos>topPos>(tmpY + (dragableBoxesArray[no]['obj'].offsetHeight))){
                    destinationObj = dragableBoxesArray[no]['obj'].parentNode;
                    dragableBoxesArray[no]['obj'].parentNode.appendChild(rectangleDiv);	
                    rectangleDiv.style.display = 'block';	
                    objFound = true;				
                }
            }
        }
    }
    if(!objFound){
        for(var no=1;no<=numberOfColumns;no++){
            if(!objFound){
                var obj = document.getElementById('dragableBoxesColumn' + no);			
                var left = getLeftPos(obj)/1;						
					
                var width = obj.offsetWidth;
                if(leftPos>left && leftPos<(left+width)){
                    destinationObj = obj;
                    obj.appendChild(rectangleDiv);
                    rectangleDiv.style.display='block';
                    objFound=true;		
                }				
            }
        }		
    }
    setTimeout('okToMove=true',5);
}
	
function stop_dragDropElement(){
    if(dragDropCounter<10){
        dragDropCounter = -1
        return;
    }
    dragDropCounter = -1;
    if(transparencyWhenDragging){
        dragObject.style.filter = null;
        dragObject.style.opacity = null;
    }		
    dragObject.style.position = 'static';
    dragObject.style.width = null;
    if(destinationObj && destinationObj.id!=dragObject.id){
        var numericDestId = destinationObj.id.replace(/[^0-9]/g,'');
        var numericId = dragObject.id.replace(/[^0-9]/g,'');
        var ex = giveOrderId(numericId);
        var preColumnId = removeValue(ex);
        if(destinationObj.id.indexOf('dragableBoxesColumn')>=0){
            addValue(ex, numericDestId-1, null);
            dragBoxHeight(numericId, preColumnId, numericDestId);
            //Esto es cuando una box se convierte en el último item de una columna o el primero si no hay nada antes.
            destinationObj.appendChild(dragObject);
            dragableBoxesArray[numericId]['parentObj'] = destinationObj;
        }else{
            var numericColumnId = destinationObj.parentElement.id.replace(/[^0-9]/g,'');
            addValue(ex, numericColumnId-1, giveOrderId(numericDestId));
            dragBoxHeight(numericId, preColumnId, numericColumnId);
            //Esto es cuando una box se mueve entre boxes o es el primero si no hay nada antes. El id es la box que viene después.
            destinationObj.parentNode.insertBefore(dragObject,destinationObj);
            dragableBoxesArray[numericId]['parentObj'] = destinationObj.parentNode;
        }
    }else{
        if(dragObjectNextSibling){
            dragObjectParent.insertBefore(dragObject,dragObjectNextSibling);	
        }else{
            dragObjectParent.appendChild(dragObject);
        }				
    }
    autoScrollActive = false;
    rectangleDiv.style.display = 'none'; 
    dragObject = false;
    dragObjectNextSibling = false;
    destinationObj = false;
   
    documentHeight = document.documentElement.clientHeight;	
}

function getTopPos(inputObj){		
    var returnValue = inputObj.offsetTop;
    while((inputObj = inputObj.offsetParent) != null){
        if(inputObj.tagName!='HTML')returnValue += inputObj.offsetTop;
    }
    return returnValue;
}
	
function getLeftPos(inputObj){
    var returnValue = inputObj.offsetLeft;
    while((inputObj = inputObj.offsetParent) != null){
        if(inputObj.tagName!='HTML')returnValue += inputObj.offsetLeft;
    }
    return returnValue;
}
		
	
function createColumns(){
    if(!columnParentBoxId){
        alert('No parent box defined for your columns');
        return;
    }
    columnParentBox = document.getElementById(columnParentBoxId);
    var columnWidth = Math.floor(100/numberOfColumns);
    var sumWidth = 0;
    for(var no=0;no<numberOfColumns;no++){
        var div = document.createElement('DIV');
        if(no==(numberOfColumns-1))columnWidth = 99 - sumWidth;
        sumWidth = sumWidth + columnWidth;
        div.style.cssText = 'float:left;width:'+columnWidth+'%;padding:0px;margin:0px;';
        div.style.height='100%';
        div.style.styleFloat='left';
        div.style.width = columnWidth + '%';
        div.style.padding = '0px';
        div.style.margin = '0px';

        div.id = 'dragableBoxesColumn' + (no+1);
        columnParentBox.appendChild(div);
			
        var clearObj = document.createElement('HR');	
        clearObj.style.clear = 'both';
        clearObj.style.visibility = 'hidden';
        div.appendChild(clearObj);
    }

    var clearingDiv = document.createElement('DIV');
    columnParentBox.appendChild(clearingDiv);
    clearingDiv.style.clear='both';
		
}
	
function mouseoverBoxHeader(){
    if(dragDropCounter==10)return;
    var id = this.id.replace(/[^0-9]/g,'');
    document.getElementById('dragableBoxExpand' + id).style.visibility = 'visible';		
		
}
function mouseoutBoxHeader(e,obj){
    if(!obj)obj=this;
    var id = obj.id.replace(/[^0-9]/g,'');
    document.getElementById('dragableBoxExpand' + id).style.visibility = 'hidden';		
}
	
function showHideBoxContent(e,inputObj){
    if(document.all)e = event;
    if(!inputObj)inputObj=this;

    var numericId = inputObj.id.replace(/[^0-9]/g,'');
    var obj = document.getElementById('dragableBoxContent' + numericId);
    
    if(!obj.style.display){
        if (hideBoxes==1){
            obj.style.display = 'block';
            inputObj.src = src_downImage;
        }else{
            obj.style.display = 'none';
            inputObj.src = src_rightImage;
        }
    }else{
        var column = inputObj.parentElement.parentElement.parentElement.parentElement; // Box's column id.
        var columnid = column.id.replace(/[^0-9]/g,'');
        if (obj.style.display == 'block'){
            obj.style.display = 'none';
            inputObj.src = src_rightImage;
            substractHeightArray(columnid-1, boxMaxHeight+5);
        }else{
            obj.style.display = 'block';
            inputObj.src = src_downImage;
            addHeightArray(columnid-1, boxMaxHeight+5);
        }
        setHeightImages();
    }
    dragableBoxesArray[numericId]['boxState'] = obj.style.display=='block'?1:0;
    setTimeout('dragDropCounter=-5',5);
}
	
function closeDragableBox(e,inputObj){
    if(!inputObj)inputObj = this;
    var numericId = inputObj.id.replace(/[^0-9]/g,'');
    document.getElementById('dragableBox' + numericId).style.display='none';	
		
    setTimeout('dragDropCounter=-5',5);
}
	
function addBoxHeader(parentObj,notDrabable, uniqueIdentifier){
    var div = document.createElement('DIV');
    div.className = 'dragableBoxHeader';
    div.style.height = '25px';
		
    div.id = 'dragableBoxHeader' + boxIndex;
    div.onmouseover = mouseoverBoxHeader;
    div.onmouseout = mouseoutBoxHeader;
    if(!notDrabable){
        div.onmousedown = initDragDropBox;
        div.style.cursor = 'move';
    }
		
    var image = document.createElement('IMG');
    image.id = 'dragableBoxExpand' + boxIndex;
    image.src = src_rightImage;
    image.style.visibility = 'hidden';	
    image.style.cursor = 'pointer';
    image.onmousedown = showHideBoxContent;	
    div.appendChild(image);
		
    var textSpan = document.createElement('SPAN');
    textSpan.id = 'dragableBoxHeader_txt' + boxIndex;
    textSpan.innerHTML = ' ' + uniqueIdentifier;
    div.appendChild(textSpan);
    parentObj.appendChild(div);	
}
	
function addBoxContentContainer(parentObj,heightOfBox, innerHTML){
    var div = document.createElement('DIV');
    div.className = 'dragableBoxContent';
    if(opera)div.style.clear='none';
    div.id = 'dragableBoxContent' + boxIndex;
    parentObj.appendChild(div);		
    if(heightOfBox && heightOfBox/1>40){
        div.style.height = heightOfBox + 'px';
        div.setAttribute('heightOfBox',heightOfBox);
        div.heightOfBox = heightOfBox;	
        if(document.all)div.style.overflowY = 'auto';else div.style.overflow='-moz-scrollbars-vertical;';
        if(opera)div.style.overflow='auto';
        div.innerHTML = innerHTML;
    }		
}
	
function createABox(columnIndex,heightOfBox,uniqueIdentifier, innerHTML, notDragable){
    boxIndex++;
    
    var maindiv = document.createElement('DIV');
    maindiv.className = 'dragableBox';
    maindiv.id = 'dragableBox' + boxIndex;
		
    var div = document.createElement('DIV');
    div.className='dragableBoxInner';
    maindiv.appendChild(div);
		
    addBoxHeader(div,notDragable, uniqueIdentifier);
    addBoxContentContainer(div,heightOfBox, innerHTML);
    
    var obj = document.getElementById('dragableBoxesColumn' + columnIndex);		
    var subs = obj.getElementsByTagName('DIV');
    if(subs.length>0){
        obj.insertBefore(maindiv,subs[0]);
    }else{
        obj.appendChild(maindiv);
    }
    dragableBoxesArray[boxIndex] = new Array();
    dragableBoxesArray[boxIndex]['obj'] = maindiv;
    dragableBoxesArray[boxIndex]['parentObj'] = maindiv.parentNode;
    dragableBoxesArray[boxIndex]['uniqueIdentifier'] = uniqueIdentifier;
    dragableBoxesArray[boxIndex]['heightOfBox'] = heightOfBox;
    dragableBoxesArray[boxIndex]['boxState'] = 0;	// Expanded
    staticObjectArray[uniqueIdentifier] = boxIndex;
    return boxIndex;
		
}
		
function createARSSBox(columnIndex,heightOfBox, id){
    if(!heightOfBox)heightOfBox = '0';
    var tmpIndex = createABox(columnIndex,heightOfBox,id);
    if(hideBoxes==0){
        showHideBoxContent(false,document.getElementById('dragableBoxExpand' + tmpIndex));
    }
    staticObjectArray[tmpIndex] = tmpIndex;
}
	
function createHelpObjects(){
    rectangleDiv = document.createElement('DIV');
    rectangleDiv.id='rectangleDiv';
    rectangleDiv.style.display='none';
    document.body.appendChild(rectangleDiv);
}
	
function cancelSelectionEvent(e){
    if(document.all)e = event;
		
    if (e.target) source = e.target;
    else if (e.srcElement) source = e.srcElement;
    if (source.nodeType == 3)
        source = source.parentNode;
    if(source.tagName.toLowerCase()=='input')return true;
						
    if(dragDropCounter>=0)return false; else return true;	
		
}
	
function cancelEvent(){
    return false;
}
	
function initEvents(){
    document.body.onmousemove = moveDragableElement;
    document.body.onmouseup = stop_dragDropElement;
    document.body.onselectstart = cancelSelectionEvent;
    document.body.ondragstart = cancelEvent;	
    documentHeight = document.documentElement.clientHeight;	
}
		
function boxesFromArray(arrayOrdenes){
    for (var j = 0; j < arrayOrdenes.length; j++){
        dia = arrayOrdenes[j];
        for (var i = 0; i < dia.length; i++){
            addValue(dia[i][0], j, null);
            dia.reverse();
            finalid = '<a onclick="cargarAJAX(\'formTrabajos.php?id=' +dia[i][0] + '\',\'formOrdenes\')" href="#">Id Orden - ' +dia[i][0] + '</a>';
            html = dia[i][1];
            createBox(j+1, finalid, html);
            dia.reverse();
            addHeightArray(j, boxMinHeight);
        }
    }
    setHeightImages();
}

function createBox(columnIndex, id, innerHTML){
    var tmpIndex = createABox(columnIndex, boxMaxHeight, id, innerHTML);
    if(hideBoxes==0){
        showHideBoxContent(false,document.getElementById('dragableBoxExpand' + tmpIndex));
    }
    staticObjectArray[tmpIndex] = tmpIndex;
}

/* Delete all boxes */
function deleteAllDragableBoxes(){
    var divs = document.getElementsByTagName('DIV');
    for(var no=0;no<divs.length;no++){
        if(divs[no].className=='dragableBox')closeDragableBox(false,divs[no]);	
    }
}
	
/* Disable drag for a box */
function disableBoxDrag(boxIndex){
    document.getElementById('dragableBoxHeader' + boxIndex).onmousedown = '';
    document.getElementById('dragableBoxHeader' + boxIndex).style.cursor = 'pie.php';		
}

function addValue(itemId, columnId, preId){
    if (preId != null){
        var arraux = new Array();
        for (var j = 0; j < resids[columnId].length; j++){
            if (resids[columnId][j] == preId){
                arraux.push(itemId);
            }
            arraux.push(resids[columnId][j]);
        }
        resids[columnId] = arraux;
    }else{
        resids[columnId].push(itemId);
    }
}

function removeValue(itemId){
    var found = 0;
    for (var i = 0; i < resids.length; i++){
        var arraux = new Array();
        for (var j = 0; j < resids[i].length; j++){
            if (resids[i][j] != itemId){
                arraux.push(resids[i][j]);
            }else{
                found = i;
            }
        }
        resids[i] = arraux;
    }
    return found;
}

function giveOrderId(mainDivId){
    var div = document.getElementById('dragableBoxHeader_txt'+mainDivId);
    var header = div.innerHTML;
    aux = header.replace(/<a(.*?)\">/g, '');
    return aux.replace(/[^0-9]/g, '');    
}

function initDragableBoxesScript(){
    createColumns();	// Always the first line of this function
    createHelpObjects();	// Always the second line of this function
    initEvents();	// Always the third line of this function
    resids=new Array(new Array(),new Array(),new Array(),new Array(),new Array(),new Array());
    dragableBoxesArray = new Array();
    boxIndex = 0;
    imgHeight = new Array(0,0,0,0,0,0);
}

function dragBoxHeight(id, preColumn, postColumn){
    var obj = document.getElementById('dragableBoxContent' + id);
    if (obj.style.display == 'block'){
        substractHeightArray(preColumn, boxMaxHeight + 5 + boxMinHeight);
        addHeightArray(postColumn-1, boxMaxHeight + 5 + boxMinHeight);
    }else{
        substractHeightArray(preColumn, boxMinHeight+5);
        addHeightArray(postColumn-1, boxMinHeight+5);
    }
    setHeightImages();
}

function addHeightArray(column, height){
    var num = parseInt(height);
    var ex = imgHeight[column];
    ex = parseInt(ex) + num;
    imgHeight[column] = parseInt(ex);
}

function substractHeightArray(column, height){
    var num = parseInt(height);
    var ex = imgHeight[column];
    if (ex >= num){
        ex = parseInt(ex) - num;
    } else{
        ex = 0;
    }
    imgHeight[column] = parseInt(ex);
}

function getHighestHeight(){
    var height=0;
    for (var i = 0; i < imgHeight.length; i++){
        if (imgHeight[i] > height){
            height = imgHeight[i];
        }
    }
    return height;
}

function setHeightImages(){
    var x=document.images
    for (var i = 0; i < 5; i++){
        x[i].height=parseInt(getHighestHeight())+15;
    }
}